<template>
  <div class="category-list">
    <n-card>
      <n-space vertical>
        <n-space justify="space-between">
          <h2>分类管理</h2>
          <n-button type="primary" @click="showAddModal = true">
            <template #icon><AddOutline /></template>
            添加分类
          </n-button>
        </n-space>
        
        <n-tree
          block-line
          :data="categoryTree"
          :node-props="nodeProps"
          :render-suffix="renderSuffix"
        />
      </n-space>
    </n-card>
    
    <!-- 添加/编辑分类模态框 -->
    <n-modal v-model:show="showAddModal" preset="card" :title="formData.id ? '编辑分类' : '添加分类'" style="width: 500px;">
      <n-form ref="formRef" :model="formData" :rules="rules">
        <n-form-item label="分类名称" path="name">
          <n-input v-model:value="formData.name" placeholder="请输入分类名称" />
        </n-form-item>
        <n-form-item label="父分类" path="parentId">
          <n-tree-select
            v-model:value="formData.parentId"
            :options="parentOptions"
            placeholder="选择父分类（不选则为顶级分类）"
            clearable
          />
        </n-form-item>
        <n-form-item label="排序" path="sort">
          <n-input-number v-model:value="formData.sort" :min="0" placeholder="排序值" />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="showAddModal = false">取消</n-button>
          <n-button type="primary" @click="handleSave">保存</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, h, onMounted, computed } from 'vue'
import { categoryApi } from '@/api/category'
import { 
  NCard, NSpace, NTree, NButton, NModal, NForm, NFormItem, 
  NInput, NTreeSelect, NInputNumber, NPopconfirm, NIcon, useMessage 
} from 'naive-ui'
import { AddOutline, CreateOutline, TrashOutline } from '@vicons/ionicons5'

const message = useMessage()

const categoryTree = ref([])
const allCategories = ref([])
const showAddModal = ref(false)

const formData = ref({
  id: null,
  name: '',
  parentId: 0,
  sort: 0
})

const rules = {
  name: { required: true, message: '请输入分类名称', trigger: 'blur' }
}

const parentOptions = computed(() => {
  const buildOptions = (categories, parentId = 0, level = 0) => {
    return categories
      .filter(c => c.parentId === parentId && c.id !== formData.value.id)
      .map(c => ({
        label: '　'.repeat(level) + c.name,
        value: c.id,
        children: buildOptions(categories, c.id, level + 1)
      }))
  }
  return [
    { label: '顶级分类', value: 0 },
    ...buildOptions(allCategories.value)
  ]
})

const buildTree = (categories, parentId = 0) => {
  return categories
    .filter(c => c.parentId === parentId)
    .map(c => ({
      key: c.id,
      label: c.name,
      data: c,
      children: buildTree(categories, c.id)
    }))
}

const nodeProps = ({ option }) => ({
  onClick() {
    // 可以添加点击节点的逻辑
  }
})

const renderSuffix = ({ option }) => {
  return h(NSpace, { size: 'small' }, () => [
    h(NButton, {
      size: 'small',
      onClick: () => handleEdit(option.data)
    }, {
      icon: () => h(NIcon, null, { default: () => h(CreateOutline) })
    }),
    h(NPopconfirm, {
      onPositiveClick: () => handleDelete(option.data.id)
    }, {
      trigger: () => h(NButton, {
        size: 'small',
        type: 'error'
      }, {
        icon: () => h(NIcon, null, { default: () => h(TrashOutline) })
      }),
      default: () => '确定删除这个分类吗？'
    })
  ])
}

const loadCategories = async () => {
  try {
    const data = await categoryApi.getAllCategories()
    allCategories.value = data
    categoryTree.value = buildTree(data)
  } catch (error) {
    console.error(error)
  }
}

const handleEdit = (category) => {
  formData.value = { ...category }
  showAddModal.value = true
}

const handleDelete = async (id) => {
  try {
    await categoryApi.deleteCategory(id)
    message.success('删除成功')
    loadCategories()
  } catch (error) {
    console.error(error)
  }
}

const handleSave = async () => {
  try {
    if (formData.value.id) {
      await categoryApi.updateCategory(formData.value.id, formData.value)
      message.success('更新成功')
    } else {
      await categoryApi.addCategory(formData.value)
      message.success('添加成功')
    }
    showAddModal.value = false
    formData.value = { id: null, name: '', parentId: 0, sort: 0 }
    loadCategories()
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  loadCategories()
})
</script>

